package com.zzx.config;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;
import java.time.LocalDateTime;

/**
 * @Author: zzx
 * @Date: 2025/6/13 21:22
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 获取当前登录用户ID（示例，实际实现需要根据项目情况调整）
     */
    private Long getCurrentUserId() {

        return UserContext.getUserId();
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        // 设置创建人和创建时间
        metaObject.setValue("createBy", UserContext.getUserId());
        metaObject.setValue("createTime", LocalDateTime.now());
        metaObject.setValue("updateBy", UserContext.getUserId());
        metaObject.setValue("updateTime", LocalDateTime.now());
        if (!ObjectUtils.isEmpty(UserContext.getCompanyId())) {
            metaObject.setValue("companyId", UserContext.getCompanyId());
        }
        handleFiled(metaObject,"parentId","0");

    }

    @Override
    public void updateFill(MetaObject metaObject) {

        // 更新时只需要更新修改人和修改时间
        metaObject.setValue("updateBy", UserContext.getUserId());
        metaObject.setValue("updateTime", LocalDateTime.now());
        if (!ObjectUtils.isEmpty(UserContext.getCompanyId())) {
            metaObject.setValue("companyId", UserContext.getCompanyId());
        }
        handleFiled(metaObject,"parentId","0");
    }

    /**
     * 字段处理
     * @param metaObject
     * @param filed
     * @param defaultValue
     */
    public static void handleFiled(MetaObject metaObject,String filed,String defaultValue){
        Object entity = metaObject.getOriginalObject();
        Class<?> clazz = entity.getClass();

        try {
            Field field = clazz.getDeclaredField(filed); // 获取 parentId 字段

            // 检查字段是否被 TableField 注解标记，并且 exist = true（默认就是 true）
            if (field.isAnnotationPresent(TableField.class)) {
                TableField tableField = field.getAnnotation(TableField.class);
                if (!tableField.exist()) {
                    // 存在注解但 exist=false，表示不是数据库字段，跳过
                    return  ;
                }
            }

            // 如果字段存在且是数据库字段，则执行填充逻辑
            if (ObjectUtils.isEmpty(metaObject.getValue(filed))) {
                metaObject.setValue(filed, defaultValue);
            }

        } catch (NoSuchFieldException e) {
            // parentId 字段不存在，跳过填充
            return;
        }
    }
}

